package com.yupi.project.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yupi.project.model.entity.Post;
import com.yupi.project.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.Assertions;
import org.springframework.boot.CommandLineRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取初始帖子列表
 */
// 取消注释后，每次启动 springboot 项目时会执行一次 run 方法
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

    // [编程知识星球](https://yupi.icu) 零基础快速入门编程，不走弯路！30+ 原创学习路线和专栏、1000+ 编程精华文章、500+ 编程学习指南、20T+ 编程资源汇总

    @Override
    public void run(String... args) {
        // 1. 获取数据
        String json = "{\n" +
                "  \"pageSize\": 12,\n" +
                "  \"sortOrder\": \"descend\",\n" +
                "  \"sortField\": \"_score\",\n" +
                "  \"tags\": [],\n" +
                "  \"searchText\": \"简历\",\n" +
                "  \"current\": 1,\n" +
                "  \"reviewStatus\": 1,\n" +
                "  \"hiddenContent\": true,\n" +
                "  \"type\": \"all\"\n" +
                "}";
        String url = "https://api.codefather.cn/api/search/";
        String result = HttpRequest
                .post(url)
                .body(json)
                .execute()
                .body();
//       System.out.println(result);
        // 2. json 转对象
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        System.out.println(map);
        // !!!!!!!!!!取完数一定要先做非空判断（增加程序的健壮性）
        JSONObject data = (JSONObject) map.get("data");
        JSONObject searchPage = (JSONObject) data.get("searchPage");
        JSONArray records = (JSONArray) searchPage.get("records");
        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tempRecord = (JSONObject) record;
            Post post = new Post();
            post.setTitle(tempRecord.getStr("title"));
            post.setContent(tempRecord.getStr("description"));
            JSONArray tags = (JSONArray) tempRecord.get("tags");
            List<String> tagList = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(tagList));
            post.setUserId(1L);
            postList.add(post);
        }
        // 3. 数据入库
        boolean b = postService.saveBatch(postList);
        System.out.println(b);
    }
}